gpt4 book ai didi

c++ - std::atomic & 的模板特化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:38 24 4
gpt4 key购买 nike

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

关于c++ - std::atomic<double> & 的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com