Home > Net >  C Template Argument Deduction with Additional Specified Template Arguments
C Template Argument Deduction with Additional Specified Template Arguments

Time:07-11

I have encountered an issue with template argument deduction. The following complies without issues, the compiler can deduce the template argument:

template<size_t a_size>
class DummyBase {
public:
    DummyBase() = delete;

    constexpr DummyBase(const char (& i)[a_size]) {

    }

};
constexpr const auto dummy = DummyBase{"f"};

However, the following does not compile and the compile gives me an error that I have not provided enough arguments:

template<int useless, size_t a_size>
class DummyBase {
public:
    DummyBase() = delete;

    constexpr DummyBase(const char (& i)[a_size]) {

    }

};

constexpr const auto dummy = DummyBase<1>{"f"};

The only change is that I have provided an additional (useless) template argument. The compile cannot deduce it and for this reason I am providing an explicit value. If I understood the theory correctly, the compiler should then try to deduce additional template arguments which were not explicitly provided. However, it either doesn't try to deduce the argument or it is suddenly unable to deduce it despite no change in the information provided for it to be deduced. (Btw, I am pretty sure taht this is the correct order for the template parameters but just for safety I tried it with reversed order and it didn't work either)

Could someone tell me what is going on and if/how I can fix it?

CodePudding user response:

Unfortunately, "Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place." - https://en.cppreference.com/w/cpp/language/class_template_argument_deduction

You could use a wrapper function to do what you want, but it won't work with the constructor itself.

  • Related