我有这个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() );
}

09-09 20:02
查看更多