1

所以给定一个函数 f 有没有办法为某些单独的不相关的类定义特定的行为,没有一些宏 foo

例如替换/完成相同事情的方式:

//p for param

template<typename T> 
T f(T p){ // some default op}; 

template<>
T f<float>(T p)
{ return 2*p; }

template<>
T f<double>(T p)
{ return 2*p; }

template<>
T f<int>(T p)
{ return 2*p; }

template<>
T f<std::string>(T p)
{ //return p copies of the string appended together; }

template<>
T f<std::vector>(T p)
{ //return the vector's element's copied}

// etc

不,我不喜欢正常的过载。理想情况下类似于模板

if T in [int, float, double]
T f(T p) { return 2*p; }

else // 定义默认的其他行为。你可以在 python 中做到这一点。

无论如何要根据T的类别做出决定?我能想到的一个可能的解决方案是非常......不漂亮的是使用 typeid 和 demangling。

假设由于某种原因你有一个超泛型函数和大约 15 个不同的类,写出所有使用重载都不是很好。

4

2 回答 2

5

如果我正确理解了您的问题,您是否想列出与所有其他类型的处理方式不同的类型?

如果是这种情况,请列出所需类型并使用元函数来确定 T 是否在返回 true 或 false 的类型列表中。

然后使用 enable_if 在函数实现之间切换。

#include <boost\mpl\vector.hpp>
#include <boost\mpl\contains.hpp>

typedef boost::mpl::vector<char,int,unsigned,long,unsigned long> types;
template<class T>
typename std::enable_if<boost::mpl::contains<types,T>::value, T>::type 
    foo(T t) 
{
    std::cout << "special foo\n";
    return t;
}

template<class T>
typename std::enable_if<boost::mpl::not_<boost::mpl::contains<types,T>>::type::value, T>::type 
    foo(T t) 
{
    std::cout << "normal foo\n";
    return t;
}
void main()
{
    foo(1);   //calls special foo because int is in the list
    foo(1.1); //calls normal foo because float is not in the list
}

更新: boost.MPL 已过时,如果您有 C++11 支持,请使用brigand

于 2013-06-28T19:19:38.860 回答
0

在我看来,您需要相当正常的(非模板)函数重载:

float f(float p)
{ return 2*p; }

double f(double p)
{ return 2*p; }

int f(int p)
{ return 2*p; }

std::string f(std::string p)
{ //return p copies of the string appended together; }

std::vector f(std::vector p)
{ //return the vector's element's copied}
于 2013-06-28T17:15:26.320 回答