0

Consider following

#include <iostream>

template <typename T, bool B>
struct C {
    using value_type = T;

    value_type f(value_type v);
};

template <bool B>
auto C<int, B>::f(value_type v) -> value_type {
    return v;
}

int main(int argc, char * argv[]) {
    C<int, true> c;
    std::cout << c.f(5) << std::endl;
    return 0;
}

Using g++ 4.9 I get error

test.cpp:11:26: error: 'C::f' declared as an 'inline' variable
inline auto C::f(value_type v) -> value_type {
test.cpp:11:26: error: template definition of non-template 'auto C::f'
test.cpp:11:26: error: 'value_type' was not declared in this scope

Problem is with value_type. It will be working when I replace this with typename C<int, B>::value_type but this is much longer and specially in real world applications it could be very long (my case). It there a way to make this work with short variant?

PS: It works with full template specialisation but I have to have only partial specialisation.

tomas789
  • 1,280
  • 1
  • 9
  • 21
  • what are you trying to do, and why are you typedefing the template param – aaronman Aug 13 '13 at 23:43
  • 1
    There is no such thing as a partial specialization of a function. `template int C::f(int);` declares a member of the partial class specialization `template class C;`, which must first be defined. – aschepler Aug 14 '13 at 00:02

1 Answers1

2

When you use a template, indeed you are defining a new type, even for template specialization.

So, the correct way for your program to work is redifining the specialization completely.

#include <iostream>

template <typename T, bool B>
struct C {
    T f(T v);
};

template <bool B>
struct C<int,B> {
  int f(int v) {
    return v;
  }
};

int main(int argc, char * argv[]) {
    C<int, true> c;
    std::cout << c.f(5) << std::endl;
    return 0;
}
Amadeus
  • 10,199
  • 3
  • 25
  • 31
  • This definitely works but I want to avoid this because I have about 13 specialisations and my real C class is quite complex - it has about 23 methods. Repeating this much code is not long time maintainable. – tomas789 Aug 14 '13 at 05:27
  • One solution is to put all common code in a base class and derive from it for each specialization. – Amadeus Aug 14 '13 at 05:30