Question

Hi :) I've looked around about this question and there seem to be a lot of related posts, but none of the answers so far could solve my problem. If you know about a post that answers this specific question, please let me know which one and I'll delete this post.

Here is what I'm trying to do; I have a class with one template argument, which default value corresponds to a template specialization. So far (see code below), it doesn't compile. What bugs me is that the similar case with two template arguments, and partial template specialization compiles and works fine.. :/

What am I doing wrong?


CASE 1: Two Template Arguments (compiles and works)

header

#include <iostream>

struct Special {};

template <class T, class U = Special>
class Bird
{
public:
    inline void operator() () { sing(); }
    inline void sing() const { std::cout << "Piu piu piu" << std::endl; }

private:
    T t; U u;
};

template <class T>
class Bird<T,Special>
{
public:
    inline void operator() () {}

private:
    T t; Special u;
};

cpp

int main()
{
    Bird<double,int> a;
    Bird<double> b;

    a(); b();
}

CASE 2: One Template Argument (does not compile)

header

#include <iostream>

struct Special {};

template <class U = Special>
class Bird
{
public:
    inline void operator() () { sing(); }
    inline void sing() const { std::cout << "Piu piu piu" << std::endl; }

private:
    U u;
};

template <>
class Bird<Special>
{
public:
    inline void operator() () {}

private:
    Special u;
};

cpp

int main()
{
    Bird<int> a;
    Bird b;

    a(); b();
}

I get an error: missing template arguments before 'b'. Thanks in advance for taking the time to read this! :)

Was it helpful?

Solution

Bird is a class template, so you always have to use the angular brackets. Unlike for function templates, in case you want to use default template arguments you can omit them, but the angle brackets have to be there:

Bird<> b;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top