2013-02-28 41 views
0

我定义的函数:C++模板函数字符串类型不匹配?

template<class T> 
inline void _assert(const string& message, T expected, T actual); 

我一直在使用它来断言2个整数是平等的。但是,当我有:

_assert("Modifies(15, v) for v value", "h", varTable->getVarName(list.at(0))); 
              ^returns std::string 

它不工作:

Error 1 error C2782: 'void _assert(const std::string &,T,T)' : template parameter 'T' is ambiguous h:\dropbox\sch\cs3202\code\test\testqueryevaluator\testgetcandidatelist.cpp 183 

为什么? 2个字符串不是同一类型?

+0

因为一个参数是一个'为const char *',而另一种'的std :: string'。 – 2013-02-28 14:52:14

回答

2

你你提供给_assert()功能getVarName()返回std::string,但第二个参数是const char[]类型(衰变为const char*)的。

这两种类型不相同,因此类型扣除无法找到T的有效匹配项。

为了解决这个问题,你可以换你的字符串文字"h"std::string对象:

_assert(
    "Modifies(15, v) for v value", 
    string("h"), // <== Wrap the string literal 
    varTable->getVarName(list.at(0)) 
    ); 

或者你可以只修改_assert()函数模板,以便它不会强制预期值和实际值是同类型:

template<typename T, typename Y> 
inline void _assert(const string& message, T expected, U actual); 

但请注意:如果您正在使用内部_assert相等比较(operator ==)比较预期值和实际值,让河畔如果你想比较字符串,你的TU不会被推断为const char*;否则,你的比较不会达到你的预期。

+0

'std :: string string(“h”); assert(“h”== string.c_str());'失败(指针比较)。所以放弃第一个例子,而是使用'std :: string'比较。 – Zeta 2013-02-28 15:05:57

+0

@ Zeta:正确。没有考虑到'_assert'会通过平等做比较。让我编辑 – 2013-02-28 15:09:54

+0

实际上,我猜你可以通过使用'static_assert(std :: is_convertible :: value,“无法在_assert中将T转换为U)”来调出最后一个版本; _assert(message,expected,T(actual));'或类似的东西。 – Zeta 2013-02-28 15:12:47

0

你的问题是"h"const char*类型,你的第二个参数是std::string类型,所以它不能找出你想要的。

你应该让他们相同的类型:

_assert("Modifies(15, v) for v value", std::string("h"), varTable->getVarName(list.at(0))); 

或更改功能,采取两种不同的PARAMS:

template<class T, class U> 
inline void _assert(const string& message, T expected, U actual); 
相关问题