【发布时间】:2013-04-22 15:22:03
【问题描述】:
嗯,VC2012 中的一个奇怪的问题我似乎无法弄清楚通过 const 引用将 const 指针传递给模板参数是非 const 指针的模板类的函数的语法,即:
template<typename T>
struct Foo
{
void Add( const T& Bar ) { printf(Bar); }
};
void main()
{
Foo<char*> foo;
const char* name = "FooBar";
foo.Add(name); // Causes error
}
所以我在这里简化了我的问题,但基本上我希望“添加”的参数有一个 const T 即 const char*。我试过了:
void Add( const (const T)& Bar );
typedef const T ConstT;
void Add( const (ConstT)& Bar );
void Add( const typename std::add_const<T>::type& Bar );
这些都不起作用。我得到的确切错误是:
error C2664: 'Foo<T>::Add' : cannot convert parameter 1 from 'const char *' to 'char *const &'
with
[
T=char *
]
Conversion loses qualifiers
我可以看到是正确的,但是如何在没有 const 将 'name' 转换为非 const 的情况下解决它。
【问题讨论】:
-
你得到什么错误信息?