我有这个MCVE:
#include <stdio.h>
#include <atomic>
template<typename T> void assertVariableHasBeenSet( T, const char * );
template<> void assertVariableHasBeenSet<std::atomic<double> &>
( std::atomic<double> & myDouble,
const char * variableName
)
{
printf( "Double:%s=%f\n", variableName, myDouble.load() );
};
int main()
{
std::atomic<double> myDoubleAtomic {23.45};
assertVariableHasBeenSet( myDoubleAtomic, "myDoubleAtomic" );
}
我得到这个编译器错误:
getType.cpp: In function ‘int main()’:
getType.cpp:14:61: error: use of deleted function ‘std::atomic<_Tp>::atomic(const std::atomic<_Tp>&) [with _Tp = double]’
assertVariableHasBeenSet( myDoubleAtomic, "myDoubleAtomic" );
^
In file included from getType.cpp:2:0:
/usr/local/include/c++/4.9.4/atomic:169:7: note: declared here
atomic(const atomic&) = delete;
^
getType.cpp:4:27: error: initializing argument 1 of ‘void assertVariableHasBeenSet(T, const char*) [with T = std::atomic<double>]’
如何将std::atomic<double>
引用传递给专用模板?在正常功能中,它是可能的。
在这种情况下,T
将被推断为std::atomic<double>
,而不是std::atomic<double> &
。然后将始终调用主模板而不是专门化。
您可以明确指定模板参数,例如
assertVariableHasBeenSet<std::atomic<double> &>(myDoubleAtomic, "myDoubleAtomic");
或者申请重载。
template<typename T> void assertVariableHasBeenSet( T, const char * );
void assertVariableHasBeenSet( std::atomic<double> & myDouble,
const char * variableName
)
{
printf( "Double:%s=%f\n", variableName, myDouble.load() );
}
你的问题在这里:
template<typename T> void assertVariableHasBeenSet( T, const char * );
将选择主要模板,因为myDoubleAtomic
的类型为std::atomic<double>
,而不是std::atomic<double> &
。
主模板尝试按值传递T
,需要副本。 std::atomic
有一个删除的拷贝构造函数导致该错误。
您应该告诉编译器显式使用哪种类型:
assertVariableHasBeenSet<std::atomic<double> &>(myDoubleAtomic, "myDoubleAtomic" );
首先要做的是重载决策。在重载分辨率期间,类型T
被推断为std::atomic<double>
。接下来确定适当的专业化。没有专门的版本,使用主模板。 std::atomic<double>&
的专业化将永远不会通过演绎找到。
有两种方法可以解决这个问题(我没有考虑明确指定类型的解决方案):
T&&
,因为这将推导T
为std::atomic<double>&
。template<>
和<std::atomic<double>&>
。