C++ compiler does not check if a method exists in template class - c++

I came across with the following program in C++:
template <class T>
class Val {
protected:
T x0, x;
public:
Val(T t = 1) : x0(t), x(1) {}
T val() { return x; }
void promote() { this->promote_value(); }
};
For some reason Val<int>(4).val(); works fine even though there is no method promote_value(). I tried to remove the templates:
class OtherVal {
protected:
int x0, x;
public:
OtherVal (int t = 1) : x0(t), x(1) {}
int val() { return x; }
void promote() { this->promote_value(); }
};
But now I get an error:
error: ‘class OtherVal’ has no member named ‘promote_value’; did you mean ‘promote’?
Why does C++ behave like this?

Template class methods are not instantiated until they are used. Once you try calling promote() or even get its address like this &Val<int>::promote then you'll get an error.
From the C++ standard:
§ 17.8.1.10 An implementation shall not implicitly instantiate a function
template, a variable template, a member template, a non-virtual member
function, a member class, a static data member of a class template,
or a substatement of a constexpr if statement (9.4.1), unless such
instantiation is required.

Templates have always worked this way, principally to facilitate their use.
Because Val<int>(4).val(); doesn't call promote, that function is not compiled for your particular instantiation of that template so the compiler does not issue a diagnostic.
Many metaprogramming techniques depend on this behaviour.

Related

Why type deduction fails for a class member?

Let's assume that we have this small code:
template<typename T>
struct Test {
Test(T t) : m_t(t) {}
T m_t;
};
int main() {
Test t = 1;
}
This code easily compiles with [T=int] for Test class. Now if I write a code like this:
template<typename T>
struct Test {
Test(T t) : m_t(t) {}
T m_t;
};
struct S {
Test t = 1;
};
int main() {
S s;
}
This code fails to compile with the following error:
invalid use of template-name 'Test' without an argument list
I need to write it like Test<int> t = 1; as a class member to work. Any idea why this happens?
The reason
struct S {
Test t = 1;
};
does not work is because you aren't actually doing Test t = 1;. An in class initializer is just a convenient way to tell the compiler what value to initialize t with when one is not provided. What "actually" gets generated is
struct S {
S() : t(1) {} // created by the compiler
Test t;
};
and here you can more easily see that t isn't specified with an initializer until you call the constructor.
There is a difference between your two snippets - first Test t = 1 declares, defines, and initializes a new variable while the second only declares a member variable and specifies how it might be initialized.
The default member initializer is relevant only in the context of a constructor without t in its member initializer list and there can easily be multiple constructors, each initializing t in different way.
The following is valid C++, what should type of t be deduced to?
struct S {
Test t = 1;
S(){}
S(int):t(1){}
S(double):t(true){}
};
If this were to be supported, you hit the implementation issue of making type/size/layout of the class dependent on the definition of constructors which are likely in different translation units. Therefore it would make it impossible to define include classes such as S (if one moved the definitions to some .cpp) via header files.

a call to a method from base template fails to compile [duplicate]

This question already has an answer here:
Why can I call base template class method from derived class
(1 answer)
Closed 2 years ago.
I have a template struct which inherits another template struct. It fails compilation in different compilers (in VS2017 and clang on linux). A simple change in the code fixes it.
The code is:
template<typename T>
struct base {
int GetValue2() { return 0; }
};
template<typename T>
struct derived : public base<T>
{
int GetValue() { return GetValue2(); }
};
int main() {
derived<int> a;
return 1;
}
If I change the line
int GetValue() { return GetValue2(); }
to:
int GetValue() { return this->GetValue2(); }
everything compiles just fine.
Does anyone have an idea what's going on?
There is a two-stage name lookup here.
In GetValue(), GetValue2 is not used in a dependent context, so the compiler will look for a name declared at the enclosing namespace scope (which is the global scope here).
It will not look into the base class, since that is dependent and you may declare specializations of Base even after declaring Derived, so the compiler can't really know what i would refer to. If there is no global variable i, then you will get an error message.
In order to make it clear that you want the member of the base class, you need to defer lookup until instantiation time, at which the base class is known. For this, you need to access i in a dependent context, by either using this->i (remember that this is of type Derived*, so is obviously dependent), or using Base::i. Alternatively, Base::i might be brought into scope by a using-declaration.
template<typename T>
struct base {
int GetValue2() { return 0; }
};
template<typename T>
struct derived : public base<T>
{
int GetValue_using() {
using base<T>::GetValue2; // won't compile with gcc, place it outside the function (ok with clang and msvc)
return GetValue2();
}
int GetValue_this() { return this->GetValue2(); }
int GetValue_base() { return base<T>::GetValue2(); }
};
int main() {
derived<int> a;
return 1;
}

template class method instantiation when a virtual unrelated method in the base class causes compilation failure on MSVC

Is the following code legal C++?
MS Visual C++ fails, but gcc and clang are fine: https://godbolt.org/z/vsQOaW
It could be an msvc bug, but wanted to check first:
struct Base {
virtual void junk() = 0;
};
template <class T>
struct Derived : Base {
void junk() override {
T::junkImpl();
}
void otherMethod() {
}
};
template <class T>
struct NotDerived {
void junk() {
T::junkImpl();
}
void otherMethod() {
}
};
struct TypeWithJunk {
void junkImpl() {
}
};
struct TypeWithoutJunk {};
void reproduce(NotDerived<TypeWithoutJunk>* ndt, Derived<TypeWithoutJunk>* dt) {
// works - junk is not used, not instantiated
ndt->otherMethod();
// fails on MSVC - junk is instantiated even if not used
dt->otherMethod();
}
junk may get instantiated just like the rest of virtual functions because it is required to populate vtable. So all the compilers seem to demonstrate conforming behavior:
17.8.1 Implicit instantiation [temp.inst]
9 … It is unspecified
whether or not an implementation implicitly instantiates a virtual member function of a class template if
the virtual member function would not otherwise be instantiated.

Member is inaccessible

class Example{
public:
friend void Clone::f(Example);
Example(){
x = 10;
}
private:
int x;
};
class Clone{
public:
void f(Example ex){
std::cout << ex.x;
}
};
When I write f as a normal function, the program compiles successful. However, when I write f as a class member, this error occurs.
Screenshot:
The error you're seeing is not a root-cause compilation error. It is an artifact of a different problem. You're friending to a member function of a class the compiler has no earthly clue even exists yet,much less exists with that specific member.
A friend declaration of a non-member function has the advantage where it also acts as a prototype declaration. Such is not the case for a member function. The compiler must know that (a) the class exists, and (b) the member exists.
Compiling your original code (I use clang++ v3.6), the following errors are actually reported:
main.cpp:6:17: Use of undeclared identifier 'Clone'
main.cpp:17:25: 'x' is a private member of 'Example'
The former is a direct cause of the latter. But doing this instead:
#include <iostream>
#include <string>
class Example;
class Clone
{
public:
void f(Example);
};
class Example
{
public:
friend void Clone::f(Example);
Example()
{
x = 10;
}
private:
int x;
};
void Clone::f(Example ex)
{
std::cout << ex.x;
};
int main()
{
Clone c;
Example e;
c.f(e);
}
Output
10
This does the following:
Forward declares Example
Declares Clone, but does not implement Clone::f (yet)
Declares Example, thereby making x known to the compiler.
Friends Clone::f to Example
Implements Clone::f
At each stage we provide what the compiler needs to continue on.
Best of luck.

Why are function template specializations not allowed inside a class?

After having found answers to many of my questions on stackoverflow, I have now come up against a question of which I can't find the answer and I hope that someone is willing to help me!
My problem is that I want to do an explicit templatization of a function inside a class in C++. My compiler (g++) and a look in the C++ standard (§14.7.3) tells me that this specialization has to be done in the namespace in which the class is declared. I understand that this implies that I cannot put the specialization inside the class, but I don't see the point of this restriction! Does anyone know if there is a good reason for not letting the specializations be made inside the class?
I know that there are workarounds, e.g. to put the function inside a struct, but I want to understand why the language has this design. If there is a good reason for not allowing specialized functions inside the class, I guess I should know it before trying to work around it.
Thanks in advance!
To make my question a little bit more precise: Here is some code from a test example which illustrates what I want to do:
#include <cstdio>
namespace MalinTester {
template <size_t DIMENSIONALITY>
class SpecializationTest {
public:
SpecializationTest() {
privateVariable = 5;
};
virtual ~SpecializationTest() {};
void execute() {
execute<DIMENSIONALITY>();
};
private:
int privateVariable;
template <size_t currentDim>
static void execute() {
printf("This is the general case. Current dim is %d. The private variable is %d.\n", currentDim, privateVariable);
execute<currentDim-1>();
}
template <>
static void execute<0>() {
printf("This is the base case. Current dim is 0.\n");
}
};
This is not possible; g++ says:
SpecializationTest_fcn.h:27: error: explicit specialization in non-namespace scope ‘class MalinTester::SpecializationTest<DIMENSIONALITY>’
SpecializationTest_fcn.h:28: error: template-id ‘execute<0>’ in declaration of primary template
If I put the function execute outside the class, in the name space MalinTester, it will look like this:
#include <cstdio>
namespace MalinTester {
template <size_t DIMENSIONALITY> class SpecializationTest {};
template <size_t currentDim>
void execute() {
printf("This is the general case. Current dim is %d. The private variable is %d.\n", currentDim, privateVariable);
execute<currentDim-1>();
}
template <>
void execute<0>() {
printf("This is the base case. Current dim is 0.\n");
}
template <size_t DIMENSIONALITY>
class SpecializationTest {
public:
SpecializationTest() {};
virtual ~SpecializationTest() {};
void execute() {
MalinTester::execute<DIMENSIONALITY>();
};
private:
int privateVariable = 5;
};
};
};
and I cannot use privatevariable in the templatized versions of execute, as it is private in the class. I really want it private, as I want to have my data encapsulated as far as possible.
Of course I can send privateVariable as an argument to the function, but I think it would be more beautiful to avoid this, and what I really wonder is if there is a good reason for the C++ standard not to allow explicit specialization as in the first code example above.
#Arne Mertz: This is the workaround I have tried, but it doesn't allow using privateVariable either. And most of all, I wonder if it is a good idea to do like this. As I'm not allowed to make specializations of member functions, maybe I shouldn't do specializations of functions encapsulated in structs inside the class either.
#include <cstdio>
namespace MalinTester {
template <size_t DIMENSIONALITY>
class SpecializationTest {
public:
SpecializationTest() {
privateVariable = 5;
};
virtual ~SpecializationTest() {};
void execute() {
Loop<DIMENSIONALITY, 0>::execute();
};
private:
int privateVariable;
template <size_t currentDim, size_t DUMMY>
struct Loop {
static void execute() {
printf("This is the general case. Current dim is %d.\n", currentDim);
Loop<currentDim-1, 0>::execute();
}
};
template <size_t DUMMY>
struct Loop<0, DUMMY> {
static void execute() {
printf("This is the base case. Current dim is 0.\n");
}
};
};
};
Base specialization:
In .h:
template <class T>
class UISelectorSlider : public UISelectorFromRange<T> {
public:
UISelectorSlider();
virtual ~UISelectorSlider();
private:
float width;
float getPositionFromValue(T value);
};
In .cpp under same namespace:
template <>
float UISelectorSlider<MVHue>::getPositionFromValue(MVHue value)
{
return width * (float)value / 360.0;
}
If you want specialized function within specialized class:
Inside class add (.h) (private function):
private:
template <int I>
void foo();
Specialization inside .cpp:
template <>
template <>
void UISelectorSlider<MVHue>::foo<3>()
{
// you can access private fields here
}
UPDATE:
But you cant write something like this:
template <class T>
template <>
void UISelectorSlider<T>::foo<3>()
{
// you can access private fields here
}
You will get: error: enclosing class templates are not explicitly specialized.
It does not matter is this definition inside class or in namespace. The point is that this is not exact partial specialization - this function does not have defined context class (which members you want to call). In other words - when you specialize member you actually try specialize the whole containing class, but not the member itself. And compiler cant do that because class is not yet defined completely. So this is restriction by template design. And if it actually worked - templates would be full equivalent to simple macros.
(And you probably can will solve your task with some macro magic.)