I'm working on a program right now and to test template classes (which I will need) I wrote a small (and buggy, chances are 2 or 3 logic bugs in it, my goal is to get it to compile) stack class. What I want to do is to compile it to a static library (.a) then link it with the main program.
The error is:
main.cpp:(.text+0x1c): undefined reference to `Stack<int>::Stack()'
main.cpp:(.text+0x31): undefined reference to `Stack<int>::push(int)'
main.cpp:(.text+0x42): undefined reference to `Stack<int>::push(int)'
main.cpp:(.text+0x4e): undefined reference to `Stack<int>::pop()'
main.cpp:(.text+0x5d): undefined reference to `Stack<int>::pop()'
collect2: error: ld returned 1 exit status
This is the header file:
/* stack.h */
#ifndef _STACK_INCLUDED_
#define _STACK_INCLUDED_
template<typename T>
struct Node
{
T* node;
Node<T>* next;
};
template<typename T>
class Stack
{
private:
Node<T>* bottom;
public:
Stack();
Stack(T first);
Stack(T* arr, int amount);
void push(T push);
T* pop();
};
/* I added the following prototypes in an attempt to correct the error,
did not work*/
template<typename T>
Stack<T>::Stack();
template<typename T>
Stack<T>::Stack(T first);
template<typename T>
Stack<T>::Stack(T* arr, int amount);
template<typename T>
void Stack<T>::push(T push);
template<typename T>
T* Stack<T>::pop();
#endif
Here is the implementation file:
/* stack.cpp */
#include "../heads/stack.h"
#define null (void*)0
template<typename T>
Stack<T>::Stack() {
bottom = null;
}
template<typename T>
Stack<T>::Stack(T first) {
push(first);
}
template<typename T>
Stack<T>::Stack(T* arr, int amount)
{
int i;
for(i=0;i<amount; i++)
{
push(arr[i]);
}
}
template<typename T>
void Stack<T>::push(T push)
{
Node<T>* tmp = new Node<T>();
tmp->node = push;
tmp->next = null;
Node<T>* node = bottom;
while(node->next != null)
{
node = node->next;
}
node->next = tmp;
}
template<typename T>
T* Stack<T>::pop()
{
int i=0;
Node<T>* node = bottom;
while(node->next != null)
{
i++;
node = node->next;
}
node = bottom;
for(;i>1;i++)
{
node = node->next;
}
Node<T>* res = node->next;
node->next = null;
return res->node;
}
You might have noticed the header file is included: "../heads/stack.h", this is because the structure looks like so:
- root
-- CLASSNAME
--- implementation of CLASSNAME
-- heads
--- all the headers
-- obj
--- object files (compiled)
--bin
---final output
.
The makefile looks like so:
CC=g++
CFLAGS=-c -fpermissive -Wall
LFLAGS=-llua
OBJ=obj
BIN=bin
HS=heads
all: $(OBJ)/bind.a $(OBJ)/stack.a $(OBJ)/main.o
$(CC) $(LFLAGS) -o $(BIN)/main $(OBJ)/main.o $(OBJ)/bind.a $(OBJ)/stack.a
$(OBJ)/bind.o: binds/bind.cpp $(HS)/bind.h
$(CC) $(CFLAGS) binds/bind.cpp -o $(OBJ)/bind.o
$(OBJ)/bind.a: $(OBJ)/bind.o
ar -cvq $(OBJ)/bind.a $(OBJ)/bind.o
$(OBJ)/main.o:
$(CC) $(CFLAGS) main/main.cpp -o $(OBJ)/main.o
$(OBJ)/stack.o: $(HS)/stack.h stack/stack.cpp
$(CC) $(CFLAGS) stack/stack.cpp -o $(OBJ)/stack.o
$(OBJ)/stack.a: $(OBJ)/stack.o
ar -cvq $(OBJ)/stack.a $(OBJ)/stack.o
clean:
touch $(OBJ)/dummy
rm $(OBJ)/*
Compiler: g++ 4.7.2 (gcc-multilib)
OS: Arch Linux (x86_64) (kernel 3.6.6-1)
You can get the whole file here (I'm doing multiple test, so don't mind the -llua flag and other files, you can change the Makefile if needed, I just want to figure this out).
After some research and testing, I noticed that the symbols aren't being exported, (nm obj/stack.o shows nothing, while nm obj/bind.o does. same thing for (.a)).
However I could not find any reference to what to do in this case.
You can't make a lib for every possible template parameters, but you can for some types.
A templated class is used to generate code of a class that taking the given type.
When there is a instance using it, it will generate the actual class, otherwise, it will be simply omitted when compile.
According to Compile header-only template library into a shared library? this is possible by using Explicit Instantiation, and make the types you declared into the lib, and let the rest to generate in compile.
Related
Or at least I think it is.
Consider the following code
#include <iostream>
#include <memory>
struct BaseBase {
virtual void foo() = 0;
virtual ~BaseBase(){}
};
template <typename Derived>
struct Base : BaseBase{
void foo() override{
static_cast<Derived*>(this)->foo();
}
};
struct D1 : Base<D1> {};
struct Unrelated {};
// no runtime polymorphism
template <typename SDerived>
struct SBase{
void foo() {
static_cast<SDerived*>(this)->foo();
}
};
struct SD1 : SBase<SD1> {};
template <typename T, typename ...Args>
void doFoo(Args&&... args){
T* t = new T(std::forward<Args>(args)...);
t->foo();
}
int main(){
doFoo<Unrelated>(); //compile time error, foo not found in unrelated
doFoo<SD1>(); //runtime crash
doFoo<D1>(); //runtime crash
return 0;
}
I was hoping the compiler would be nice enough to check for the existence of fooat compile time in doFoo but in both cases, with virtual in base, and without virtual in base the code compiles just fine but crashes at runtime.
Why is this?
Edit: clang setup
clang version 4.0.1 (tags/RELEASE_401/final)
Target: x86_64-unknown-linux-gnu
with doFoo<Unrelated>() commented out compiles.
and g++ setup
gcc version 7.1.1 20170630 (GCC)
compiles with doFoo<Unrelated>() commented out.
This is because both of the classes have a function called foo. It's present in the base class for each class.
However, all that function does is call itself, which will eventually result in a stack overflow.
g++ 5.2.1 fails to compile when it encounters a private method's address in a template deduction context whereas clang 3.5 only discards the specialization.
g++ 5.2.1 can access protected members of parents/friends in a class template parameter list when clang 3.5 sometimes fail to do so.
Which are wrong in which cases?
More precisely:
Should the compiler cause a hard error when trying to access a non accessible protected/private member in a template deduction context? Am I doing something wrong in my first example?
If not, should the compiler discard a specialization when trying to access (in a template deduction context) a protected member owned by:
a base class of this specific specialization
a class which declared this specific instantiation as a friend
a friend class which declared any instantiation of this template as a friend
The first question seems to have already been answered here (and the answer seems to be "no, the code isn't ill-formed and the compiler should simply discard this specialization"). However, since it's a prerequisite to the second question (and g++ 5.2.1 doesn't seem to agree), I want to be absolutely sure that it's g++ 5.2.1 which is wrong, not me.
Longer version with examples
I would like to make traits able to detect whether some functions/methods are implemented, even if they are protected members of some class (if you find this odd, I'll explain why I want to do this at the end of this question so that you can tell me I'm completely wrong, should learn how to design my classes, and maybe suggest me a cleaner way to do so).
My problem is that each of my attempts fail on either clang or g++ (oddly enough, not both at the same time): Sometimes it compiles but don't provide the expected result, sometimes it doesn't compile at all.
Even though it seems it isn't practical, I at least want to know when the compilers are faulty, and when I'm writing ill-formed code. Hence this question.
I use the C++11 dialect, and my clang version is actually the compiler provided with XCode 5 i.e. Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn).
To better illustrate what my problem is, here is a minimal exemple where clang compiles but g++ 5.2.1 doesn't:
#include <iostream>
#include <type_traits>
#include <utility>
struct PrivateFoo {
private:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
template<class C, class = void>
struct has_foo : std::false_type {};
template<class C>
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
std::true_type {};
int main() {
std::cout << std::boolalpha;
std::cout << "PrivateFoo has foo: " << has_foo<PrivateFoo>::value << '\n';
return 0;
}
output with clang 3.5:
PrivateFoo has foo: false
g++ 5.2.1 errors:
access_traits.cpp : [in instantiation of] ‘struct has_foo<PrivateFoo>’ :
access_traits.cpp:37:61: required from here
access_traits.cpp:7:8: [error]: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:32:56: [error]: [in context]
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
^
access_traits.cpp:7:8: [error]: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:32:56: [error]: [in context]
struct has_foo<C, void_t<check_signature<void(C::*)(), &C::foo>>> :
^
access_traits.cpp: [in function] ‘int main()’:
access_traits.cpp:7:8: erreur: ‘void PrivateFoo::foo()’ is private
void foo() {}
^
access_traits.cpp:37:42: [error]: [in context]
std::cout << "PrivateFoo has foo: " << has_foo<PrivateFoo>::value << '\n';
(text in brackets is translated, it was originally in my native language)
Here is an example where both compile but disagree on whether foo is accessible or not:
#include <iostream>
#include <type_traits>
#include <utility>
struct ProtectedFoo {
protected:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class = void>
struct has_foo_helper : std::false_type {};
template<class C>
struct has_foo_helper<C, void_t<decltype(std::declval<C>().foo())>> :
std::true_type {};
}
template<class C>
struct has_public_or_protected_foo : protected C {
template<class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<has_public_or_protected_foo<C>>::value;
};
int main() {
std::cout << std::boolalpha;
std::cout << "ProtectedFoo has foo: ";
std::cout << has_public_or_protected_foo<ProtectedFoo>::value << '\n';
return 0;
}
output with clang 3.5:
ProtectedFoo has foo: false
output with g++ 5.2.1:
ProtectedFoo has foo: true
and finally here is an example where both compile and agree that they should be able to access foo:
#include <iostream>
#include <type_traits>
#include <utility>
struct ProtectedFoo {
protected:
void foo() {}
};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class D, class = void>
struct has_foo_helper : std::false_type {};
template<class C, class D>
struct has_foo_helper<C, D, void_t<check_signature<void(C::*)(), &D::foo>>> :
std::true_type {};
}
template<class C>
struct has_public_or_protected_foo : protected C {
template<class, class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<C, has_public_or_protected_foo<C>>::value;
};
int main() {
std::cout << std::boolalpha;
std::cout << "ProtectedFoo has foo: ";
std::cout << has_public_or_protected_foo<ProtectedFoo>::value << '\n';
return 0;
}
output with clang 3.5:
ProtectedFoo has foo: true
output with g++ 5.2.1:
ProtectedFoo has foo: true
Also here is a more complete example which summarizes it all:
#include <iostream>
#include <type_traits>
#include <utility>
/* test classes */
struct PublicFoo {
void foo() {}
};
struct ProtectedFoo {
protected:
void foo() {}
};
struct PrivateFoo {
private:
void foo() {}
};
struct NoFoo {};
/* utilities */
// reimplement C++17's std::void_t
template<class...>
struct void_type {
typedef void type;
};
template<class... T>
using void_t = typename void_type<T...>::type;
// dummy class used to check whether a pointer to (possibly member) function
// exists with the good signature
template<class T, T>
struct check_signature {};
/* traits */
namespace detail {
template<class C, class D, class = void>
struct has_foo_helper : std::false_type {};
template<class C, class D>
struct has_foo_helper<C, D, void_t<check_signature<void(C::*)(), &D::foo>>> :
std::true_type {};
template<class C, class = void>
struct may_call_foo_helper : std::false_type {};
template<class C>
struct may_call_foo_helper<C, void_t<decltype(std::declval<C>().foo())>> :
std::true_type {};
}
template<class C>
struct has_foo : detail::has_foo_helper<C, C> {};
template<class C>
struct may_call_foo : detail::may_call_foo_helper<C> {};
template<class C>
struct has_protected_foo : protected C {
template<class, class, class>
friend class detail::has_foo_helper;
static constexpr bool value =
detail::has_foo_helper<C, has_protected_foo<C>>::value;
};
template<class C>
struct may_call_protected_foo : protected C {
template<class, class>
friend class detail::may_call_foo_helper;
static constexpr bool value =
detail::may_call_foo_helper<may_call_protected_foo<C>>::value;
};
/* test */
template<class T>
void print_info(const char* classname) {
std::cout << classname << "...\n";
// comment this if you want to compile with g++
//*
std::cout << "has a public method \"void foo()\": ";
std::cout << has_foo<T>::value << '\n';
std::cout << "has a public or protected method \"void foo()\": ";
std::cout << has_protected_foo<T>::value << '\n';
//*/
std::cout << "has a public method \"foo\" callable without any arguments: ";
std::cout << may_call_foo<T>::value << '\n';
std::cout << "has a public or protected method \"foo\" callable without any "
"arguments: ";
std::cout << may_call_protected_foo<T>::value << '\n';
std::cout << '\n';
}
int main() {
std::cout << std::boolalpha;
// both g++ 5.2.1 and clang 3.5 compile
print_info<PublicFoo>("PublicFoo");
// g++ 5.2.1 fails to compile has_foo, clang 3.5 compiles fine
print_info<ProtectedFoo>("ProtectedFoo");
// g++ 5.2.1 fails to compile, clang 3.5 compiles fine
print_info<PrivateFoo>("PrivateFoo");
// both g++ 5.2.1 and clang 3.5 compile
print_info<NoFoo>("NoFoo");
return 0;
}
Why do I want to do this?
Skip this if you don't want to know the details. I just wrote this in case you were either shocked by the idea of me trying to detect protected members and/or curious about why I asked this question.
I was writing some kind of iterator template classes built out of other iterators and I got tired of writing multiple specializations depending on whether these iterators meet some requirements (ForwardIterator, BidirectionalIterator, RandomAccessIterator... although my iterators actually meet some relaxed versions of these concepts, they are kind of "proxy iterators" but it's not really relevant here).
For instance, if I only use random access iterators, my new custom iterator could (and should) also be some kind of random access iterator, hence implement operator+=, operator+, operator-=, operator-, operator<, operator>, operator<= and operator>=. However, some of these operators can easily be deduced from others, and they should only be defined if all the iterator I use are random access iterators.
I finally thought I'd just make something to provide default implementations if available. However, I wasn't really fond of the std::allocator_traits way as it wouldn't be very handy and readable with iterators (plus, I wouldn't be able to use them with some standard utilities).
The design I finally choose consists in having a template class which will build a full-fledged iterator out of a minimal implementation (for instance containing only the operator+=, operator==, operator* and operator> definitions) by having an inheritance chain of "mixins" (whose ancestor is my minimal iterator) detecting whether the functions/methods they need are available in their base class and defining the default methods if they are.
There is a subtility though. Sometimes I want to return a reference to the final iterator (for instance in Iterator& operator++()). If it's a method I redefine, I can easily solve that with CRTP and a static_cast, but what if my mixins don't touch that method at all?
I figured I should probably forbid the use of any method I haven't touched and inherit my minimal iterator with the protected access specifier... but now then my traits fail to detect the availability of some protected methods.
Therefore, I'd like to have traits able to detect whether some members are available with either public or protected visibility.
I have the below working code available on coliru.stacked-crooked.com.
As static std::false_type check(...) is duplicated, I wonder if we could factorize it. For instance within a base class. As pointed out by Jonathan Wakely my attempt at the bottom of my question compiles using Clang, but not using GCC.
I have tried many possibilities but it seems impossible to use decltype on inherited template static function using GCC.
Questions:
1. Is GCC-4.9 compliant with C++11 standard on this point?
2. What is the GCC-compliant workaround to use decltype on inherited template static member function?
#include <type_traits>
#include <iostream>
#include <string>
template<typename T>
struct is_addable
{
template<typename U> static std::false_type check(...);
template<typename U> static auto check(int)
-> decltype( std::declval<U>() + std::declval<U>(), std::true_type{});
using type = decltype(check<T>(0));
};
template<typename T>
struct is_multiplicable
{
template<typename U> static std::false_type check(...);
template<typename U> static auto check(int)
-> decltype( std::declval<U>() * std::declval<U>(), std::true_type{});
using type = decltype(check<T>(0));
};
int main()
{
std::cout <<"is_addable\n";
std::cout <<" long: "<< is_addable<long>::type::value <<'\n';
std::cout <<" string: "<< is_addable<std::string>::type::value <<'\n';
std::cout <<" void: "<< is_addable<void>::type::value <<'\n';
std::cout <<"is_multiplicable\n";
std::cout <<" long: "<< is_multiplicable<long>::type::value <<'\n';
std::cout <<" string: "<< is_multiplicable<std::string>::type::value <<'\n';
std::cout <<" void: "<< is_multiplicable<void>::type::value <<'\n';
}
One of my attempts
Edit: added template<typename U> as pointed out by Jonathan Wakely
struct default_check
{
template<typename U>
static std::false_type check(...);
};
template<typename T>
struct is_addable : default_check
{
using default_check::check;
template<typename U> static auto check(int)
-> decltype( std::declval<U>() + std::declval<U>(), std::true_type{});
using type = decltype(check<T>(0));
};
GCC-4.9.2 fails on coliru.stacked-crooked.com
> g++ -std=c++11 -Wall -pedantic -Wextra -Wfatal-errors main.cpp
main.cpp: In instantiation of 'struct is_addable<void>':
main.cpp:38:63: required from here
main.cpp:19:30: error: no matching function for call to 'is_addable<void>::check(int)'
using type = decltype(check<T>(0));
^
compilation terminated due to -Wfatal-errors.
Clang-3.4.1 succeeds on godbolt.org
> clang++ -std=c++11 -Wall -pedantic -Wextra -Wfatal-errors
Your default_check::check is not a template, so you can't call it like check<T>(0)
The solution is simply to make it a function template:
struct default_check
{
template<typename T> // <-- ADD THIS LINE
static std::false_type check(...);
};
Clang accepts that, but GCC still won't compile that (not sure why) so I'd just give up on default_check and write check everywhere you need it, as you had originally. It's clearer anyway.
I was going to suggest simplifying your syntax by defaulting the type parameter of the check function template in the derived classes:
template<typename T>
struct is_addable : default_check
{
using default_check::check;
template<typename U = T> static auto check(int)
-> decltype(std::declval<U>() + std::declval<U>(), std::true_type{});
using type = decltype(check(0));
};
but clang and gcc disagree on how to resolve the overload set. GCC apparently doesn't believe that the non-template check inherited from default_check is viable.
In any case, especially if you're going to have several of these traits, it would seem simpler to factor out "SFINAE check of a binary operation" into a template:
template<class...>
struct voider { using type = void; };
template<class...Ts>
using void_t = typename voider<Ts...>::type;
template <class T, class U, class BinaryOperation, class Enable = void>
struct is_binop_able_ : std::false_type {};
template <class T, class U, class BinOp>
struct is_binop_able_<T, U, BinOp, void_t<
decltype(std::declval<BinOp>()(
std::declval<T>(), std::declval<U>()))>> :
std::true_type {};
template <class T, class U, class BinOp>
using is_binop_able = typename is_binop_able_<T,U,BinOp>::type;
and create an alias for each of the desired traits that instantiates
that template with a generic function object type that implements the desired operation:
#define RETURNS(...) \
noexcept(noexcept(__VA_ARGS__)) \
->decltype(__VA_ARGS__) { \
return (__VA_ARGS__); \
}
struct plus {
template <class T, class U>
auto operator()(T t, U u) RETURNS(t + u)
};
template<class T, class U = T>
using is_addable = is_binop_able<T, U, plus>;
struct multiplies {
template <class T, class U>
auto operator()(T t, U u) RETURNS(t * u)
};
template<class T, class U = T>
using is_multiplicable = is_binop_able<T, U, multiplies>;
It's slightly less code per trait template, and you get handy reusable generic binary function object types as a nice side effect. The other nice side effect is that both GCC and clang compile it correctly: DEMO.
As #0x499602D2 states in a comment, the void specializations of the C++14 standard library function objects are almost exactly identical to the generic binary function objects implemented herein. If your library has C++14 implementations of them you could simply use them instead of writing your own (DEMO with GCC only, clang up to 3.6 blows up on is_multiplicable<std::string>, although clang trunk compiles it correctly):
template<class T, class U = T>
using is_addable = is_binop_able<T, U, std::plus<>>;
template<class T, class U = T>
using is_multiplicable = is_binop_able<T, U, std::multiplies<>>;
When compiling with -Weffc++ and extending boost::iterator_facade, I get the compiler warning: base class has a non-virtual destructor. What can I do to fix this?
Here is sample code:
#include <iostream>
#include <boost/iterator/iterator_facade.hpp>
struct my_struct_t {
int my_int;
my_struct_t() : my_int(0) {
}
};
class my_iterator_t : public boost::iterator_facade<
my_iterator_t,
my_struct_t const,
boost::forward_traversal_tag
> {
private:
friend class boost::iterator_core_access;
my_struct_t my_struct;
public:
my_iterator_t() : my_struct() {
}
void increment() {
++ my_struct.my_int;
}
bool equal(my_iterator_t const& other) const {
return this->my_struct.my_int == other.my_struct.my_int;
}
my_struct_t const& dereference() const {
return my_struct;
}
};
int main() {
my_iterator_t my_iterator;
std::cout << my_iterator->my_int << "\n";
++my_iterator;
std::cout << my_iterator->my_int << "\n";
return 0;
}
I compile on Fedora 19 like this:
$ g++ test.cpp -std=gnu++0x -Weffc++ -o test
Here is the actual warning:
g++ test.cpp -std=gnu++0x -Weffc++ -o test
test.cpp:10:7: warning: base class ‘class boost::iterator_facade<my_iterator_t, const my_struct_t, boost::forward_traversal_tag>’ has a non-virtual destructor [-Weffc++]
class my_iterator_t : public boost::iterator_facade<
^
Thanks.
-Weffc++ option enables warnings about violations of the some style guidelines from Scott Meyers’ Effective C++ book. Your code violates the Item 7: Make destructors virtual in polymorphic base classes. So the compiler isn't complaining about your iterator, it's about the base class: boost::iterator_facade. I don't think you can eliminate the warning by modify your own code. As to why virtual destructor in polymorphic base classes are so important, a good answer is here.
I have a problem with SFINAE with G++ 4.1.2.
The following code works properly for 4.6:
#include <stdio.h>
class Test
{
public:
int x;
};
template <typename T>
inline T f(T v) { return v;} // Definition #2
template <typename T>
inline typename T::x f(T v) { return v.x; } // Definition #1
int main()
{
Test t;
t.x = 100;
printf("Test.x = %d\n", f(t));
printf("int = %d\n", f(10));
}
Naturally, the output is:
Test.x = 100
int = 10
I need something like to this to work on g++ 4.1.2, any ideas ? Frankly, I don't understand how there could be so much difference between these two compilers!
Or if you have an alternative for it, that would be great. Something with templates! Or MACROS...
I actually solved a part of my problem...
But for this case here, it should be template<class T> and not template<typename T>...
So just an half Hi-Five to myself. But for the second part, I used another approach, it was annoying to do, but it worked.