std :: atomic的模板特化 &

问题描述 投票:5回答:3

我有这个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>引用传递给专用模板?在正常功能中,它是可能的。

c++ c++11 templates template-specialization
3个回答
5
投票

在这种情况下,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() );
}

2
投票

你的问题在这里:

template<typename T> void assertVariableHasBeenSet( T, const char * );

将选择主要模板,因为myDoubleAtomic的类型为std::atomic<double>,而不是std::atomic<double> &

主模板尝试按值传递T,需要副本。 std::atomic有一个删除的拷贝构造函数导致该错误。

您应该告诉编译器显式使用哪种类型:

assertVariableHasBeenSet<std::atomic<double> &>(myDoubleAtomic,   "myDoubleAtomic" );

2
投票

首先要做的是重载决策。在重载分辨率期间,类型T被推断为std::atomic<double>。接下来确定适当的专业化。没有专门的版本,使用主模板。 std::atomic<double>&的专业化将永远不会通过演绎找到。

有两种方法可以解决这个问题(我没有考虑明确指定类型的解决方案):

  1. 声明主要模板采取转发参考T&&,因为这将推导Tstd::atomic<double>&
  2. 而不是模板专门化使用重载,即删除功能名称后的template<><std::atomic<double>&>
© www.soinside.com 2019 - 2024. All rights reserved.