简体   繁体   English

一个功能的类模板专业化

[英]Class Template Specialization for one Function

I've got a templated class that looks like this: 我有一个看起来像这样的模板化类:

template<typename T>
class TemplatedClass
{
    // ... Other functions
    void AssignTo(const T & value)
    {
        m_value = value;
    }

private:
    T m_value;
    // ...
}

that I want to work with std::atomic<> , but doesn't at the moment because std::atomic<> is non-copyable. 我想使用std::atomic<> ,但是目前不可以,因为std::atomic<>是不可复制的。

Is there any way to only re-implement the AssignTo() function, but keep using all the other functions without modification so that we can have eg TemplatedClass<std::atomic<bool> ? 有什么办法只能重新实现AssignTo()函数,而是继续使用所有其他函数而无需修改,以便我们可以使用例如TemplatedClass<std::atomic<bool> I've thought about using std::enable_if or template specialization, but haven't come up with an elegant solution. 我曾考虑过使用std::enable_if或模板专门化,但还没有提出一个优雅的解决方案。

#include <type_traits>

template <typename T>
class TemplatedClass
{
public:
    void AssignTo(const T& value)
    {
        if constexpr (std::is_copy_assignable_v<T>) {
            m_value = value;
        } else {
            // Something else
        }
    }

private:
    T m_value;
};

DEMO 演示


For atomic-only types, replace std::is_copy_assignable_v<T> with !is_atomic_v<T> : 对于仅原子类型,将std::is_copy_assignable_v<T>替换为!is_atomic_v<T>

template <typename>
constexpr bool is_atomic_v = false;

template <typename T>
constexpr bool is_atomic_v<std::atomic<T>> = true;

Is there any way to only re-implement the AssignTo() function, but keep using all the other functions without modification so that we can have eg TemplatedClass<std::atomic<bool> ? 有什么办法只能重新实现AssignTo()函数,而是继续使用所有其他函数而无需修改,以便我们可以使用例如TemplatedClass<std::atomic<bool>

Do you mean something as follows? 您的意思如下吗?

template <typename>
struct isAtomic : public std::false_type
 { };

template <typename T>
struct isAtomic<std::atomic<T>> : public std::true_type
 { };

template <typename T>
constexpr auto isAtomic_v = isAtomic<T>::value;

template <typename T>
class TemplatedClass
 {
    public: 
       // ... Other functions

       template <typename U = T>
       std::enable_if_t<false == isAtomic_v<U>> AssignTo(const T & value)
        { m_value = value; }

       template <typename U = T>
       std::enable_if_t<true == isAtomic_v<U>> AssignTo(const T & value)
        { /* ??? */ }

    private:
       T m_value;
    // ...
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM