c++ - 没有宏的模板特化类型列表?

标签 c++ templates

所以给定一个函数 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。

假设出于某种原因你有一个 super 通用函数和大约 15 个不同的类,写下全部使用重载并不漂亮。

最佳答案

如果我对你的问题的理解正确,你想列出一个类型的列表,这些类型的处理方式应该与所有其他类型不同?

如果是这种情况,请列出所需的类型并使用元函数来确定 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

关于c++ - 没有宏的模板特化类型列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17370151/

相关文章:

c++ - 使用(连同)realloc 调用构造函数

c++ - 将 vector 转换为带有指向成员的指针的映射?

c++ - OpenMP 导致内部编译器错误

c++ - 是什么触发源服务器运行嵌入式命令来获取源文件的拷贝?

c++ - 在 C++ 中处理 Apache Thrift list/map 返回类型

c++ - 我可以有一个 lambda 指针数组来保存具有不同类型参数/返回值的函数吗?

c++ - 插入新节点时 BST 树错误

c++ - 可变参数模板函数的特化

c++ - 了解 C++ 模板示例

html - FreeMarker模板中字符串过长如何灵活调整列宽?