2014-10-03 41 views
1

我甚至不确定这是叫什么。如何将覆盖传递给结构模板类型或变量模板类型到函数中?

我希望做类似这样的事情......有一个函数将arg引用为带有两个模板的模板类型,但其中一个模板未设置为石头。

我的问题是我用什么来代替WHAT_DO_I_PUT_HERE来得到这个编译?我已经尝试过各种东西,比如传递void和“struct Hash”(第二个模板声明为class Hash = hash<Value>

注意:我不能使用C++ 11。

void doTest(std::tr1::unordered_set<std::string, WHAT_DO_I_PUT_HERE> &set) { 
    ... 
} 

struct HashStructOne { 
    size_t operator()(const std::string &item) const {...} 
}; 

struct HashStructTwo { 
    size_t operator()(const std::string &item) const {...} 
}; 

int main() { 
    std::tr1::unordered_set<std::string, HashStructOne> set1; 
    std::tr1::unordered_set<std::string, HashStructTwo> set2; 
    doTest(set1); 
    doTest(set2); 
} 
+0

宏'HashStructOne'和'HashStructTwo'是两种截然不同的类型。我不认为有什么方法可以在不使用模板或虚函数的情况下对两种不同类型或成员函数使用相同的函数。 – Jason 2014-10-03 16:36:59

回答

3

你可以做到以下几点:

template<typename PUT_SOMETHING_HERE> 
void doTest(std::tr1::unordered_set<std::string, PUT_SOMETHING_HERE> &set) { 
     ... 
    } 

模板参数的名称不一定是任何特殊,它只是将名称中的函数的参数,其中的模板匹配你想要这个类型被替换。

+0

当尝试使用基于以下方法调用集合时会导致编译器错误:HashStructOne:error:无法调用“doTest”的匹配函数(std :: tr1 :: unordered_set ,std :: allocator >,HashStructOne,std :: equal_to ,std :: allocator >>,std :: allocator ,std :: allocator >>,false>(&)())' – marathon 2014-10-03 16:51:09

+0

你使用的是哪个版本的编译器?只是好奇,因为你仍然在使用'tr1'命名空间... – Jason 2014-10-03 19:30:56

+0

g ++(GCC)4.1.2 20080704(Red Hat 4.1.2-50)...可悲的是我不能走得更新。 – marathon 2014-10-03 19:56:14

2

void doTest(std::tr1::unordered_set<std::string, WHAT_DO_I_PUT_HERE> &set) { 
    ... 
} 

&hellip的最简单的解决方案;只是

template< class Foo > 
void doTest(std::tr1::unordered_set<std::string, Foo>& set) 
{ 
    ... 
} 

我发现是有用的也传递类型的测试功能(输出)的名称,因为从typeid(T).name()名称不能保证可读的,特别是与G ++。

然后我这样定义

#define DO_TEST(Type) test<Type>(#Type) 
相关问题