I would like to make a template class which has two template arguments. First - N is a class of variable default set as int and second container is a container from stl and default is set as std::vector.
#include <iostream>
#include <vector>
template <class N=int,
template <class T=N, class Allocator=std::allocator<N>>
class container=std::vector>
class foo{
container<N> cont;
};
int main()
{
foo f;
}
When I created object f of above class without template arguments then the compiler wrote a folowing error:
In function 'int main()':
15:9: error: missing template arguments before 'f'
I would like foo to be equivalent to the foo<int, std::vector> declaration.
Where is an issue is my class definition?
With C++14 or before, you need to write foo<> in order to instantiate the template.
From C++17 on, it actually just works as you wrote it because of Class Template Argument Deduction. You might consider updating your C++ language version with -std=c++17 if your compiler supports it.
Related
Background
According to the C++ standard, when forward-declaring a template type with default template parameters, each of them can appear in one declaration only. For example:
// GOOD example
template <class T = void>
class Example; // forward-declaration
template <class T>
class Example {}; // definition
// GOOD example
template <class T>
class Example; // forward-declaration
template <class T = void>
class Example {}; // definition
// BAD example
template <class T = void>
class Example; // forward-declaration
template <class T = void> // ERROR: template parameter redefines default argument
class Example {}; // definition
Problem
In my code I have a lot of forward declaration in different files, so it makes sense to put my default parameters in the definition:
// foo.hpp, bar.hpp, baz.hpp, etc.
template <class T>
class Example;
// example.hpp
template <class T = void>
class Example {};
and, as expected, it all works well everywhere... except clang! I narrowed the problem down to this:
In clang, if the class template has default parameters, but they are not declared in the first forward declaration of that class, and when declaring an instance of that class no angle brackets are specified, clang ignores the default parameter and raises an error "no viable constructor or deduction guide for deduction of template arguments of ...".
Example
// GOOD example
template <class T>
class Example;
template <class T = void>
class Example {};
int main() {
Example e; // error: no viable constructor or deduction guide for deduction of template arguments of 'Example'
}
Moving = void to the forward declaration fixes the issue, but is not viable for me since my forward-decls are in different files and I don't know which one will appear first. (Also super problematic since my defaults would be in some obscure file deep in the codebase)
Changing Example e; to Example<> e; fixes the issue, but is not viable for me since I'm a library dev and don't want all my users typing <> after my classes.
Adding a forward-declaration file example_fwd.hpp with one forward-declaration and including it instead of forward declaring every time fixes the issue, but I would like to avoid this if there is a better solution.
Question
Who is right in this case: clang or the other compilers? Is this a compiler bug? How can I circumvent this issue (apart from partial solutions I described above)?
I've found #10147 (and related stackoverflow questions), but it's about template template params and also is marked as fixed over a year ago.
Edit
This looks like a bug, and is now reported on LLVM bugtracker (#40488).
I don't know who's right but...
How can I circumvent this issue (apart from partial solutions I described above)?
What about adding the following deduction rule?
Example() -> Example<>;
The following code compile (C++17, obviously) with both g++ and clang++
template <class T>
class Example;
template <class T = void>
class Example {};
Example() -> Example<>;
int main() {
Example e;
}
Considering the following:
[temp.param]/12 - The set of default template-arguments available for use is obtained by merging the default arguments from all prior declarations of the template in the same way default function arguments are [ Example:
template<class T1, class T2 = int> class A;
template<class T1 = int, class T2> class A;
is equivalent to
template<class T1 = int, class T2 = int> class A;
— end example ]
The default arguments available for
template <class T>
class Example;
template <class T = void>
class Example {};
will be the defaults arguments in the definition of Example. The two declarations above will be equivalent to have a single declaration as
template <class T = void>
class Example {};
which will effectively allow doing Example e.
The original code should be accepted. As a workaround and already suggested in max66's answer, you can provide a deduction guide that uses the default argument
Example() -> Example<>;
The standard does not make distinction whether a default template argument is defined in the definition or a declaration of a template.
Because Clang accepts the code when the default argument appears in the declaration, but not in the definition, at least one of this two behaviors is wrong. Considering [over.match.class.deduct]/1.1.1:
The template parameters are the template parameters of C followed by the template parameters (including default template arguments) of the constructor, if any.
, I am tempted to say that Clang should use the default template argument.
I think that you could avoid this bug by following a common practice:
If a declaration must be forwarded, create a dedicated header file for this forward declaration.
Define default arguments in this forward declaration file
Also include this file in the header file that provides the definition of the template.
As an example see iosfwd: libstdc++/iosfwd
You can have a "shorthand" for a class template from a namespace by only giving the name of the template. However if the class template is in a class, I have to create an alias template and write out all the template parameters and arguments - which is bad for maintainability:
namespace mynamespace {
template<template<class> class T>
class MyClass;
}
using mynamespace::MyClass; // OK, straight and simple
class MyOuterClass {
public:
template<template<class> class T>
class MyInnerClass;
};
// using MyInnerClass = MyOuterClass::MyInnerClass; // error: invalid use of template-name 'MyOuterClass::MyInnerClass' without an argument list
// template<typename... TArgs> // error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class T> class MyOuterClass::MyInnerClass'
// using MyInnerClass = MyOuterClass::MyInnerClass<TArgs...>;
template<template<class> class T> // OK, but copying the template parameter list is bad, there should be some "auto" mechanism...
using MyInnerClass = MyOuterClass::MyInnerClass<T>;
int main(){}
Run code
Can I have a "shorthand" for such a template in a simpler way?
No. There is no such way. To using statements which are used (no pun intended) to make the definition visible are actually different versions of the same keyword. One is a using declaration, and another is an alias for typedef. They work differently and provide for different (though some times similarly looking) results.
If MyOuterClass::MyInnerClass<> only had type template parameters, you could use the following variadic alias template:
template<typename... TArgs>
using MyInnerClass = MyOuterClass::MyInnerClass<TArgs...>;
However, you still have to provide the parameter pack TArgs.
Assuming C++17, if MyOuterClass::MyInnerClass<> only had non-type template parameters you could use the following variadic alias template:
template<auto... Val>
using MyInnerClass = MyOuterClass::MyInnerClass<Val...>;
I wasted countless hours to pinpoint an issue with gcc. I wanted to test our code base with another compiler to look for more warnings that Clang might have missed. I was shocked that practically half of the project stopped to compile due to failure of template argument deduction. Here I've tried to dumb my case down to the simplest piece of code.
#include <type_traits>
struct Foo
{ };
// This is a template function declaration, where second template argument declared without a default
template <typename T, typename>
void foo(const Foo & foo, T t);
// This is a template function definition; second template argument now has a default declared
template <typename T, typename = typename std::enable_if<1>::type>
void foo(const Foo & foo, T t)
{
}
int main(int argc, char ** argv)
{
foo(Foo{}, 1);
return 0;
}
Ignore a 1 in the std::enable_if<1>. Obviously it's a constant value just to not complicate things when it does not matter.
This piece of code compiles[1] with clang (3.4 through 4.0), icc (16, 17), Visual C++ (19.00.23506). Basically, I couldn't find any other c++11 compiler that, except gcc (4.8 through 7.1), does not compile this piece of code.
The question is, who's right and who's wrong here? Does gcc behave according to the standard?
Obviously this is not a critical issue. I can easily move std::enable_if to the declaration. The only victim would be aesthetics. But it is nice to be able to hide an ugly 100 characters long std::enable_if piece of code, that is not immediately relevant for the user of the library function, in the implementation.
Live example on godbolt.org.
What the standard says ([1] page 350):
The set of default template-arguments available for use with a
template declaration or definition is obtained by merging the default
arguments from the definition (if in scope) and all declarations in
scope in the same way default function arguments are (8.3.6). [
Example:
template<class T1, class T2 = int> class A;
template<class T1 = int, class T2> class A;
is equivalent to
template<class T1 = int, class T2 = int> class A;
— end example ]
So GCC is wrong here. It ignores default template arguments in declarations.
Not all declarations, only function template declarations. Class template declarations are okay:
#include <type_traits>
template <typename T, typename>
struct Foo;
template <typename T, typename = typename std::enable_if<1>::type>
struct Foo
{
T t;
};
int main()
{
Foo<int> foo;
return 0;
}
Live example on godbolt.org
Probably it is due to the nature of how non-default arguments are deduced. In the function template they are deducted from function arguments. In the class template we have to specify them explicitly.
Anyway, I have created a bug report.
I have a templated class for which I want to enable different constructors depending on the template parameter. Specifically, I want to use std::is_compound as a criterion.
SSCCE
// bla.cpp
#include <type_traits>
#include <vector>
template <typename T>
class Foo{
double bar;
public:
template<typename U=T,
class = typename std::enable_if<std::is_compound<U>::value>::type
>
Foo(typename T::value_type& b):bar(b){}
template<typename U=T,
class = typename std::enable_if<!std::is_compound<U>::value>::type
>
Foo(T b):bar(b){}
};
int main(){
double d=1.0;
Foo<std::vector<double>> f2(d); // works
Foo<double> f1(d); // compiler error
}
I get the following compilation error:
g++ -std=gnu++11 bla.cpp
bla.cpp: In instantiation of ‘class
Foo<double>’: bla.cpp:22:18: required from here bla.cpp:11:2: error:
‘double’ is not a class, struct, or union type
coliru
The problem seems to be that the first version of the constructor is being used, which fails because double::value_type does not exist. The problem is that that constructor shouldn't be in Foo<double> in the first place, because std::is_compound<double>::value is false.
Why does std::enable_if seem to be not working properly?
In typename T::value_type&, T cannot be substituted by double. Since T is a template parameter of the class template and not of the constructor template, you cannot get the overload excluded by substitution failure. SFINAE only works if parameters of the template in question are involved.
If you use typename U::value_type&, you get a substitution failure that is not an error as U is a parameter of the constructor template, not of the class template.
I'm reading some source code in stl_construct.h,
In most cases it has sth in the <>
and i see some lines with only "template<> ...".
what's this?
This would mean that what follows is a template specialization.
Guess, I completely misread the Q and answered something that was not being asked.
So here I answer the Q being asked:
It is an Explicit Specialization with an empty template argument list.
When you instantiate a template with a given set of template arguments the compiler generates a new definition based on those template arguments. But there is a facility to override this behavior of definition generation. Instead of compiler generating the definition We can specify the definition the compiler should use for a given set of template arguments. This is called explicit specialization.
The template<> prefix indicates that the following template declaration takes no template parameters.
Explicit specialization can be applied to:
Function or class template
Member function of a class template
Static data member of a class template
Member class of a class template
Member function template of a class template &
Member class template of a class template
It's a template specialization where all template parameters are fully specified, and there happens to be no parameters left in the <>.
For example:
template<class A, class B> // base template
struct Something
{
// do something here
};
template<class A> // specialize for B = int
struct Something<A, int>
{
// do something different here
};
template<> // specialize both parameters
struct Something<double, int>
{
// do something here too
};