Lourens Dijkstra
Lourens Dijkstra

Reputation: 430

Constructor with template argument deduction executes unexpected

Problem

The called constructor (That is, A::A(T)) does not execute as I expected. Calling it does compile (using GCC-8.3.0), but does not seem to execute the std::cout operator<<. Why is this?

Code

struct A {

    template <typename T>
    constexpr A(T) {
        std::cout << "A::A(T)";
    }
};

struct B {};

int main() {
    ::A a (B());
}

Why would you even do this?

I'm trying to deduce type T through template argument deduction. The object is irrelevant and therefore unnamed. I require type T to access certain data at compile-time (Among other things for static_assert). In C++, it is impossible to explicitly specify a template argument as constructor parameter, as far as I'm aware of. (So: A a = A::A<T>). I could do this in an indirect way, that is, creating a static member-function for creation, where the parameter can be specified:

struct C {
    template <typename T>
    static constexpr C create() { 
        // do whatever you want with T
        return C(); 
    }
};

However, I'm mostly just experimenting.

Upvotes: 0

Views: 68

Answers (1)

r3mus n0x
r3mus n0x

Reputation: 6144

You've came across the most vexing parse. You should define a like this instead:

::A a {B{}};

Upvotes: 2

Related Questions