简体   繁体   中英

Partial template specialization for constructor

I need a class which looks like this:

template<typename T, class S, size_t C>
class myClass
{
public:
    myClass(); // Ctor

    /*


    */
private:
S myData;
}

Where T is type of stored data, S is a container type and C is it's size. Methods won't depend on a container type, but I still need to properly initialize S. For example, let S be std::vector , I tried:

template<typename T, size_t C>
myClass<T, std::vector<T>, C>::myClass()
{

}

But I get E0040 expected identifier error.

You cannot partial specialize a method, you could partial specialize the whole class, but require some duplication.

As you can use C++17, you might tweak the implementation instead:

template<typename T, class S, size_t C>
myClass<T, S, C>::myClass()
{
    if constexpr (std::is_same_v<S, std::vector<T>>) {
        // special case
    } else {
        // regular case
    }
}

tag dipatching in another option (pre-C++17) which has the advantage to allow member initializer list:

template <typename T> struct tag{}; 

template <typename T, class S, size_t C>
class myClass
{
private:
    myClass(tag<std::vector<T>>) : myData(/*special case */) {/* special case */}

    template <typename U>
    myClass(tag<U>) : myData(/*regular case */) {/* regular case */}

public:
    myClass() : myClass(tag<S>{}) {}

private:
    S myData;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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